﻿using System.Data.Cassandra.Connection.Pool;
using System.Data.Cassandra.Extensions;

namespace System.Data.Cassandra
{
    public class CassandraConnection : IConnection, IDisposable
    {
        private static ConnectionPool Pool;
        private static Apache.Cassandra.Cassandra.Client CassandraClient;

        internal CassandraConnection(ConnectionPool connectionPool)
        {
            if (connectionPool == null)
                throw new ArgumentNullException("connectionPool", "ConnectionPool can´t be null");
            
            Pool = connectionPool;
            CassandraClient = connectionPool.Borrow();
        }

        public void ChangeDatabase(String keySpaceName)
        {
            if (String.IsNullOrWhiteSpace(keySpaceName))
                throw new ArgumentNullException("keySpaceName", "KeySpaceName can´t be null");

            CassandraClient.set_keyspace(keySpaceName);
        }

        public void Close()
        {
            Pool.Return(CassandraClient);
        }

        public String ConnectionString
        {
            get
            {
                return Pool.FirstHost + ":" + Pool.FirstPort;
            }
        }

        public Int32 ConnectionTimeout
        {
            get { return Pool.TimeoutMillisecond; }
        }

        public CassandraCommand CreateCommand()
        {
            return new CassandraCommand(CassandraClient, Pool.TimeoutMillisecond);
        }

        public string Database
        {
            get { return CassandraClient.HostName(); }
        }

        public void Dispose()
        {
            Pool.Return(CassandraClient);
        }
    }
}